#!/usr/bin/ruby
require "rubygems"
require "opengl"
require "glut"
require "m3g"
require "pp"

class MyGLUTWidget
  def initialize
    GLUT.Init
    GLUT.InitWindowSize  256, 256
    GLUT.InitDisplayMode GLUT::GLUT_DOUBLE | GLUT::GLUT_RGB | GLUT::GLUT_DEPTH
    GLUT.CreateWindow "Ruby-M3G"

    initialize_scene

    GLUT.ReshapeFunc  method(:reshape).to_proc()
    GLUT.DisplayFunc  method(:display).to_proc()
    GLUT.KeyboardFunc method(:keyboard).to_proc()
    GLUT.MouseFunc    method(:mouse).to_proc()
    GLUT.IdleFunc     method(:idle).to_proc()

  end

  def initialize_scene

    positions = M3G::VertexArray.new 4, 3, 2
    positions.values[0,4] = [1,-1,0, 1,1,-5, -1,-1,0, -1,1,-5]

    colors = M3G::VertexArray.new 4, 3, 1
    colors.values[0,4] = [255,255,255, 255,255,255, 255,255,255, 255,255,255]

    tex_coords = M3G::VertexArray.new 4, 2, 2
    tex_coords.values[0,4] = [1,0, 1,1, 0,0, 0,1]

    scale = 1
    bias  = [0,0,0]
    vertices = M3G::VertexBuffer.new
    vertices.positions = positions, scale, bias
    vertices.colors    = colors
    vertices.tex_coords[0] = tex_coords, scale, bias
    vertices.tex_coords[1] = tex_coords, scale, bias

    indices = [0,1,2, 2,1,3]
    strips  = [3, 3]
    tris = M3G::TriangleStripArray.new indices, strips

    img0, = M3G::Loader::load "yumemi.png"
    tex0 = M3G::Texture2D.new img0

    img1, = M3G::Loader::load "onnanoko.png"
    tex1 = M3G::Texture2D.new img1
    tex1.blending = M3G::Texture2D::FUNC_DECAL

    pmode = M3G::PolygonMode.new
    pmode.winding = M3G::PolygonMode::WINDING_CW
    pmode.culling = M3G::PolygonMode::CULL_FRONT
    pmode.perspective_correction_enable = true

    app = M3G::Appearance.new
    app.texture[0] = tex0
    app.texture[1] = tex1
    app.polygon_mode = pmode

    mesh = M3G::Mesh.new vertices, tris, app
    mesh.translate 0,0,2

    cam = M3G::Camera.new
    cam.translate 0,0,5

    @wld = M3G::World.new
    @wld.child << cam
    @wld.child << mesh
    @wld.active_camera = cam  

  end

  def reshape width, height
    g3d = M3G::Graphics3D::instance
    g3d.viewport = 0,0,width,height
    @wld.active_camera.perspective = 45, width/(height*1.0), 0.1, 100
  end

  def display
    g3d = M3G::Graphics3D::instance
    g3d.render @wld
    GLUT.SwapBuffers()
  end
  
  def keyboard key, x, y
    if key == 113
      exit
    end
    GLUT.PostRedisplay
  end

  def mouse button, state, x, y
  end

  def idle
   GLUT.PostRedisplay
  end

  def start
    GLUT.MainLoop
  end

end


MyGLUTWidget.new.start

